package stattracker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.swing.SwingWorker;

public class ReachBetaGamesFetcher 
{
	private static final int MAX_PAGES = 10000;
	
	ReachBetaData data;
	String standardURL, arenaURL, invasionURL;
	int totalGames;
	
	public ReachBetaGamesFetcher(ReachBetaData currentData)
	{
		data = currentData;
		
		standardURL = "http://www.bungie.net/Stats/Reach/PlayerGameHistory.aspx?player=" + data.getGamertag().replaceAll(" ", "%20") + "&vc=standard#&&li=" + MAX_PAGES;
		arenaURL = "http://www.bungie.net/Stats/Reach/PlayerGameHistory.aspx?player=" + data.getGamertag().replaceAll(" ", "%20") + "&vc=arena#&&li=" + MAX_PAGES;
		invasionURL = "http://www.bungie.net/Stats/Reach/PlayerGameHistory.aspx?player=" + data.getGamertag().replaceAll(" ", "%20") + "&vc=invasion#&&li=" + MAX_PAGES;
		
		getGames(standardURL, SearchType.STANDARD);
		System.out.println(String.format("Standard Total: %d", totalGames));
//		getGames(arenaURL, SearchType.ARENA);
//		System.out.println(String.format("Arena Total: %d", totalGames));
//		getGames(invasionURL, SearchType.INVASION);
//		System.out.println(String.format("Invasion Total: %d", totalGames));
	}
	
	private void getGames(String url, SearchType type)
	{
		boolean reachedPrev = false;
		
		try
		{
			data.moreUpdate();
			URL bungie = new URL(url);
			
			String dataEncode = URLEncoder.encode("__EVENTTARGET", "UTF-8") + "=" + URLEncoder.encode("ctl00$mainContent$recentgames$ctl00$ctl03$ctl01$pagerButton", "UTF-8");
			//dataEncode += "&" + URLEncoder.encode("__EVENTTARGET", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
			URLConnection conn = bungie.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(dataEncode);
			wr.flush();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			//BufferedReader in = new BufferedReader(new InputStreamReader(bungie.openStream()));
			String inline;
			
			while((inline = in.readLine()) != null){
				System.out.println(inline);
			}
			
			
			
			if(type == SearchType.STANDARD || type == SearchType.ARENA)
				while(!(inline = in.readLine()).contains("<td colspan=\"5\">")){}
			else if(type == SearchType.INVASION)
				while(!(inline = in.readLine()).contains("</thead><tbody>")){}
			else{} //TODO: Customs
			
			totalGames = 0;
			while((inline = in.readLine()) != null && !reachedPrev)
			{
				
				if(inline.contains("ctl00_mainContent_recentgames_ctl00") && inline.contains(data.getGamertag()))
				{
					String gametype = parseGameType(inline);
					String detailedURL = parseURL(inline);
					inline = in.readLine();
					inline = in.readLine();
					String placing = parseSimpleData(inline);
					inline = in.readLine();
					inline = in.readLine();
					String date = parseSimpleData(inline);
					inline = in.readLine();
					inline = in.readLine();
					String map = parseSimpleData(inline);
					inline = in.readLine();
					inline = in.readLine();
					String playlist = parseSimpleData(inline);
					
					//System.out.println(String.format("%s\t%s\t%s\t%s\t%s\n%s\n", gametype, placing, date, map, playlist, detailedURL));
					totalGames++;
				}
				
			}
			data.lessUpdate();
		}
		catch(MalformedURLException e){new ErrorMessage(e);}
		catch(IOException e){new ErrorMessage(e);}
		
	}
	
	private String parseURL(String html)
	{
		int start = html.indexOf("href=\"")+6;
		return "http://www.bungie.net" + html.substring(start, html.indexOf("\"", start)).replaceAll(" ", "%20");
	}
	
	private String parseSimpleData(String html)
	{
		return html.substring(html.indexOf(">")+1, html.indexOf("<", html.indexOf(">")+1));
	}
	
	private String parseGameType(String html)
	{
		String startMatch = data.getGamertag()+"\">";
		int start = html.indexOf(startMatch) + startMatch.length();
		return html.substring(start, html.indexOf("<", start));
	}
}

enum SearchType
{
	INVASION,
	ARENA,
	STANDARD,
	CUSTOM;
}
